<?php

namespace app\http\controller\admin\sys;

use app\model\SettingModel;
use app\http\controller\admin\Controller;

/**
 * 配置管理接口控制器
 */
class SettingController extends Controller
{
    /**
     * 查看配置
     *
     * @param SettingModel $model 操作模型
     * @return string
     */
    public function index(SettingModel $model)
    {
        $group = $this->container->request->get('group', '');
        if ($this->container->request->isAjax() && !empty($group)) {
            $config = $model->getConfig($group, false);
            return $this->success('ok', $config);
        }

        // 获取组别
        $groups = $model->getGroup();
        // 获取编辑权限
        $edit = $this->container->auth->check('/admin/sys/setting/edit', $this->userInfo['id']);
        return $this->fetch('sys/setting/index', [
            'groups'    => $groups,
            'edit'      => $edit
        ]);
    }

    /**
     * 新增组别
     * 
     * @param SettingModel $model 操作模型
     * @return string
     */
    public function add(SettingModel $model)
    {
        if ($this->container->request->isPost()) {
            $option = $this->container->request->post();
            $save = $model->add($option);
            if (!$save) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }

        $group = $this->container->request->get('group', '');
        $this->assign('group', $group);
        return $this->fetch('sys/setting/add');
    }

    /**
     * 编辑配置
     *
     * @param SettingModel $model 操作模型
     * @return string
     */
    public function edit(SettingModel $model)
    {
        if ($this->container->request->isPost()) {
            $option = $this->container->request->post();
            $save = $model->edit($option);
            if (!$save) {
                return $this->error($model->getError());
            }

            return $this->success('操作成功');
        }
    }
}
